import allure
from playwright.sync_api import Page
from core.model import ElementModel


class FileKeywords:
    def __init__(self, page: Page):
        self.page = page

    def upload_file(self, element_model: ElementModel, file_path: str, time_out=12):
        """
        上传文件
        :param element_model: 元素模型
        :param file_path: 文件路径
        """
        step_desc = "上传文件" if element_model.desc is None else f"在{element_model.desc}上传文件"
        with allure.step(step_desc):
            try:
                self.page.locator(element_model.selector).set_input_files(file_path, timeout=time_out*1000)
                print(f"PASS|{step_desc}成功: {file_path}")
            except Exception as e:
                print(f"FAIL|{step_desc}失败: {e}")
                raise e

    def download_file(self, element_model: ElementModel, save_path: str, time_out=12):
        """
        下载文件
        :param element_model: 元素模型
        :param save_path: 保存路径
        """
        step_desc = "下载文件" if element_model.desc is None else f"从{element_model.desc}下载文件"
        with allure.step(step_desc):
            try:
                with self.page.expect_download(timeout=time_out*1000) as download_info:
                    self.page.locator(element_model.selector).click(timeout=time_out*1000)
                download = download_info.value
                download.save_as(save_path)
                print(f"PASS|{step_desc}成功保存到: {save_path}")
            except Exception as e:
                print(f"FAIL|{step_desc}失败: {e}")
                raise e